package thread;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

import packageParser.PackageParserForServer;
import protocol.DataPackage;

public class QQServerThread extends Thread{
	private Map<String, BufferedWriter> socketList;         //存文件名和writer就可以了
	private List<String> userList;
	
	private BufferedWriter writer;
	private BufferedReader reader;
	private Socket sockets;
	public QQServerThread(Map<String, BufferedWriter> socketList, 
			List<String> userList, BufferedWriter writer, BufferedReader reader, Socket sockets) {
		this.userList = userList;
		this.socketList = socketList;
		this.writer = writer;
		this.reader = reader;
		this.sockets = sockets;
	}
	
	//QQ线程，每一个用户登录就开辟一个线程
	@Override
	public void run() {
		boolean status = true;
		while(status){
			try {
				System.out.println("wait for read line in sever ....");
				String messageString = reader.readLine();
				System.out.println(messageString + " 获得的退出包");
				ObjectMapper mapper = new ObjectMapper();
				DataPackage pack = null;
				try {
					pack = mapper.readValue(messageString, DataPackage.class);
				} catch (Exception e) {
					e.printStackTrace();    
				} 
				status = PackageParserForServer.packageParse(socketList, userList, pack);					//对package进行处理
				System.out.println(status + " 状态。。。。。。。。。。");
			} catch (Exception e) {
				status = false;
				e.printStackTrace();
				System.out.println("qq线程异常关闭");
			}
		}
		
		try {
			//关闭所有输出流
			for(String i:userList){
				BufferedWriter out = socketList.get(i);
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			socketList.clear();
			sockets.close();
			
			System.out.println("关闭所有的server服务....");
		} catch (IOException e) {
			System.out.println("关闭流时出现异常");
		}
	}
}
